package com.zzyl.job;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.jayway.jsonpath.internal.Utils;
import com.zzyl.constant.CacheConstants;
import com.zzyl.entity.AlertRule;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.service.AlertRuleService;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.DeviceDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Component
public class AlertJob {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AlertRuleMapper alertRuleMapper;

    @Autowired
    private AlertRuleService alertRuleService;

    @Scheduled(cron = "0 * * * * ?")
    // 每分钟执行一次
    public void deviceDataAlertFilter() {
        // 当参数为 null 时，通常表示不进行条件过滤，即获取所有符合条件的记录
        List<AlertRule> alertRules = alertRuleMapper.selectByFunctionId(null, null, null);
        // 获取所有规则
        if (CollUtil.isEmpty(alertRules)) {
            // 结束
            return;
        }
        // 查询所有设备上报的数据
        List<Object> deviceDataList = redisTemplate.opsForList().range(CacheConstants.DEVICE_LASTDATA_CACHE_KEY, 0, -1);
        // 如果为空，结束
        if (ObjectUtil.isEmpty(deviceDataList)) {
            return;
        }
        // 数据格式标准化处理
        // 将上报数据转成List<DeviceDataVo>
        List<DeviceDataVo> deviceDataVoList = new ArrayList<>();
        // 将数据转成List<DeviceDataVo>
        for (Object deviceData : deviceDataList) {
            // 将数据转成DeviceDataVo
            DeviceDataVo deviceDataVo = JSON.parseObject(deviceData.toString(), DeviceDataVo.class);
            // 添加到集合中
            deviceDataVoList.add(deviceDataVo);
        }


        // 对每条数据进行规则校验
        deviceDataVoList.forEach(d -> alertRuleService.alertFilter(d));


            // // 判断设备上报时间是否大于1分钟
            // if (deviceDataVo.getAlarmTime().isBefore(LocalDateTime.now().minusMinutes(1))) {
            //
            // }

        }
    }



